package com.poizon.infrastructure.common.util;

import org.yaml.snakeyaml.Yaml;

import java.util.Map;
import java.util.Properties;
/**
 *  yml转换成properties
 */
public class YamlToPropertiesConverter {
    /**
     * 将YML字符串转换为Properties对象
     *
     * @param ymlString YML字符串
     * @return Properties 对象
     */
    public static Properties convertYmlStringToProperties(String ymlString) {
        // 读取YML字符串并转换为Map
        Map<String, Object> ymlMap = loadYmlString(ymlString);

        // 将Map转换为Properties
        return convertMapToProperties(ymlMap);
    }

    /**
     * 从YML字符串中读取数据并转换为Map
     *
     * @param ymlString YML字符串
     * @return Map 对象
     */
    private static Map<String, Object> loadYmlString(String ymlString) {
        Yaml yaml = new Yaml();
        return yaml.load(ymlString);
    }

    /**
     * 将Map结构转换为Properties对象
     *
     * @param map 包含YML数据的Map
     * @return Properties 对象
     */
    private static Properties convertMapToProperties(Map<String, Object> map) {
        Properties properties = new Properties();

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof Map) {
                // 如果值还是一个map，则递归处理
                convertNestedMapToProperties((Map<String, Object>) entry.getValue(), properties, entry.getKey());
            } else {
                // 否则直接添加到properties中
                properties.setProperty(entry.getKey(), entry.getValue().toString());
            }
        }

        return properties;
    }

    /**
     * 递归处理嵌套的Map
     *
     * @param nestedMap  嵌套的Map
     * @param properties Properties对象
     * @param prefix     前缀
     */
    private static void convertNestedMapToProperties(Map<String, Object> nestedMap, Properties properties, String prefix) {
        for (Map.Entry<String, Object> entry : nestedMap.entrySet()) {
            String key = prefix + "." + entry.getKey();
            if (entry.getValue() instanceof Map) {
                convertNestedMapToProperties((Map<String, Object>) entry.getValue(), properties, key);
            } else {
                properties.setProperty(key, entry.getValue().toString());
            }
        }
    }
}
